const http = require('http');
const archiver = require('archiver');
const child_process = require('child_process');

child_process.exec('open https://github.com/login/oauth/authorize?client_id=Iv1.efb0c1bedf337e41')

const server = http.createServer(function (request, response) {
  const result = request.url.match(/\?([\s\S]+)$/);
  if (!result) {
    return response.end();
  }
  const query = new URLSearchParams(result[1]);
  publish(query.get('token'), info => {
    response.end(info);
  });
});

server.listen(8001);

function publish(token, callback) {
  const request = http.request(
    {
      hostname: '127.0.0.1',
      method: 'POST',
      path: '/publish?token=' + token,
      port: 8000,
      headers: {
        'Content-Type': 'application/octet-stream',
      },
    },
    response => {
      response.on('data', chunk => {
        callback(chunk);
      });
    }
  );

  const archive = archiver('zip', {
    zlib: { level: 9 },
  });

  archive.directory('./sample', false);
  archive.finalize();

  const pipe = archive.pipe(request);

  pipe.on('finish', () => {
    request.end();
    archive.destroy();
  });
}

